package src.leetcode.everyday.mid_1717;


import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @Author: 李逸重
 * @CreateTime: 2025-07-23
 * @Description:
 * @Version: 1.0
 */
public class maximumGain {
    public static void main(String[] args) {
        System.out.println(new Solution().maximumGain("cdbcbbaaabab", 4, 5));
    }
}


class Solution {
    String s;
    char c1, c2;
    int x, y;
    public int maximumGain(String s, int x, int y) {
        this.s = s;
        if (x > y) {
            this.c1 = 'a';
            this.c2 = 'b';
            this.x = x;
            this.y = y;
        } else {
            this.c1 = 'b';
            this.c2 = 'a';
            this.x = y;
            this.y = x;
        }
        return maxGain();
    }

    private int maxGain() {
        int ans = 0;
        int left = 0, right = 0;
        while (right < s.length()) {
            left = right;
            while (right < s.length() && s.charAt(right) != c1 && s.charAt(right) != c2) {
                left++;
                right++;
            }
            while (right < s.length() && (s.charAt(right) == c1 || s.charAt(right) == c2)) {
                right++;
            }
            ans += maxGain(left, right);
        }
        return ans;
    }

    private int maxGain(int left, int right) {
        Deque<Character> stack = new ArrayDeque<>();
        int ans = 0;
        for (int i = left; i < right; i++) {
            if (stack.isEmpty()) {
                stack.push(s.charAt(i));
                continue;
            }
            if (stack.peek() == c1 && s.charAt(i) == c2) {
                stack.pop();
                ans += x;
            } else {
                stack.push(s.charAt(i));
            }
        }
        int numa = 0, numb = 0;
        while (!stack.isEmpty()) {
            if (stack.pop() == c1) {
                numa++;
            } else {
                numb++;
            }
        }
        return ans + Math.min(numa, numb) * y;
    }
}